import Flutter
import UIKit

/// iOS端MethodChannel管理器 - 统一管理所有Flutter与iOS的通信
class ChannelManager: NSObject {
    static let shared = ChannelManager()

    // 数据通信Channel
    private var dataChannel: FlutterMethodChannel?
    // 页面交互Channel
    private var navigationChannel: FlutterMethodChannel?
    // 第三方插件Channel
    private var pluginChannel: FlutterMethodChannel?

    // 数据事件DataEventChannel
    private var dataEventChannel: DataEventChannel?

    private override init() {
        super.init()
    }

    /// 设置所有Channel
    func setupChannels(messenger: FlutterBinaryMessenger) {
        print("🔧 开始设置所有Channel...")

        setupDataChannel(messenger: messenger)
        setupNavigationChannel(messenger: messenger)
        setupPluginChannel(messenger: messenger)

        // 设置数据事件EventChannel
        setupDataEventChannel(messenger: messenger)

        print("✅ 所有Channel设置完成！")
    }

    // 新增：设置数据事件Channel
    private func setupDataEventChannel(messenger: FlutterBinaryMessenger) {
        dataEventChannel = DataEventChannel.shared
        dataEventChannel?.setupEventChannel(messenger: messenger)
        print("✅ 数据事件Channel设置完成")
    }

    // MARK: - 数据通信Channel
    private func setupDataChannel(messenger: FlutterBinaryMessenger) {
        dataChannel = FlutterMethodChannel(name: "data_channel", binaryMessenger: messenger)

        dataChannel?.setMethodCallHandler { [weak self] call, result in
            print("📱 数据Channel收到调用: \(call.method)")

            switch call.method {
            case "sendUserInfo":
                self?.handleSendUserInfo(call.arguments, result: result)
            case "getDeviceInfo":
                self?.handleGetDeviceInfo(result: result)
            default:
                result(FlutterMethodNotImplemented)
            }
        }

        print("✅ 数据通信Channel设置完成")
    }

    // MARK: - 页面交互Channel
    private func setupNavigationChannel(messenger: FlutterBinaryMessenger) {
        navigationChannel = FlutterMethodChannel(name: "navigation_channel", binaryMessenger: messenger)

        navigationChannel?.setMethodCallHandler { [weak self] call, result in
            print("📱 页面交互Channel收到调用: \(call.method)")

            switch call.method {
            case "openPageA":
                self?.handleOpenPageA(call.arguments, result: result)
            case "openPageB":
                self?.handleOpenPageB(call.arguments, result: result)
            default:
                result(FlutterMethodNotImplemented)
            }
        }

        print("✅ 页面交互Channel设置完成")
    }

    // MARK: - 第三方插件Channel
    private func setupPluginChannel(messenger: FlutterBinaryMessenger) {
        pluginChannel = FlutterMethodChannel(name: "plugin_channel", binaryMessenger: messenger)

        pluginChannel?.setMethodCallHandler { [weak self] call, result in
            print("📱 第三方插件Channel收到调用: \(call.method)")

            switch call.method {
            case "googleLogin":
                self?.handleGoogleLogin(result: result)
            case "wechatLogin":
                self?.handleWechatLogin(result: result)
            case "alipayPayment":
                self?.handleAlipayPayment(call.arguments, result: result)
            default:
                result(FlutterMethodNotImplemented)
            }
        }

        print("✅ 第三方插件Channel设置完成")
    }
}

// MARK: - 数据通信处理
extension ChannelManager {
    private func handleSendUserInfo(_ arguments: Any?, result: @escaping FlutterResult) {
        guard let userInfo = arguments as? [String: Any] else {
            result(FlutterError(code: "INVALID_ARGUMENT", message: "用户信息格式错误", details: nil))
            return
        }

        print("📱 iOS端接收到用户信息: \(userInfo)")

        // 模拟处理用户信息
        let response: [String: Any] = [
            "status": "success",
            "message": "用户信息接收成功",
            "receivedData": userInfo,
            "timestamp": Date().timeIntervalSince1970
        ]

        result(response)
    }

    private func handleGetDeviceInfo(result: @escaping FlutterResult) {
        let device = UIDevice.current
        let deviceInfo: [String: Any] = [
            "name": device.name,
            "model": device.model,
            "systemName": device.systemName,
            "systemVersion": device.systemVersion,
            "batteryLevel": device.batteryLevel,
            "isCharging": device.batteryState == .charging
        ]

        result(deviceInfo)
    }
}

// MARK: - 页面交互处理
extension ChannelManager {
    private func handleOpenPageA(_ arguments: Any?, result: @escaping FlutterResult) {
        guard arguments is [String: Any] else {
            result(FlutterError(code: "INVALID_ARGUMENT", message: "用户信息格式错误", details: nil))
            return
        }

        // 获取当前FlutterViewController
        guard let rootViewController = UIApplication.shared.windows.first?.rootViewController as? FlutterViewController else {
            result(FlutterError(code: "NAVIGATION_ERROR", message: "无法获取根视图控制器", details: nil))
            return
        }

        // 创建页面A
        let pageA = PageAViewController()

        let navController = UINavigationController(rootViewController: pageA)
        // 设置模态展示样式为全屏，这样看起来就像 push 一样
        navController.modalPresentationStyle = .fullScreen

        //  设置转场动画 - 使用正确的枚举值
        navController.modalTransitionStyle = .crossDissolve  // 淡入淡出

        rootViewController.present(navController, animated: true) {
            result(true)
        }
    }

    private func handleOpenPageB(_ arguments: Any?, result: @escaping FlutterResult) {
        guard let params = arguments as? [String: Any] else {
            result(FlutterError(code: "INVALID_ARGUMENT", message: "参数格式错误", details: nil))
            return
        }

        // 获取当前FlutterViewController
        guard let rootViewController = UIApplication.shared.windows.first?.rootViewController as? FlutterViewController else {
            result(FlutterError(code: "NAVIGATION_ERROR", message: "无法获取根视图控制器", details: nil))
            return
        }

        // 创建页面B
        let pageB = PageBViewController()
        pageB.params = params

        let navController = UINavigationController(rootViewController: pageB)
        rootViewController.present(navController, animated: true) {
            result(true)
        }
    }
}

// MARK: - 第三方插件处理
extension ChannelManager {
    private func handleGoogleLogin(result: @escaping FlutterResult) {

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let googleUserInfo: [String: Any] = [
                "status": "success",
                "provider": "google",
                "user": [
                    "id": "google_123456789",
                    "email": "testuser@gmail.com",
                    "name": "Test User",
                    "givenName": "我是原生谷歌登录",
                    "familyName": "User",
                    "picture": "https://example.com/avatar.jpg"
                ] as [String: Any],
                "accessToken": "fake_google_access_token_12345",
                "expiresAt": Date().addingTimeInterval(3600).timeIntervalSince1970,
                "timestamp": Date().timeIntervalSince1970
            ]

            print("📱 谷歌登录成功，返回数据: \(googleUserInfo)")
            result(googleUserInfo)
        }
    }

    private func handleWechatLogin(result: @escaping FlutterResult) {

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let wechatUserInfo: [String: Any] = [
                "status": "success",
                "provider": "wechat",
                "user": [
                    "openid": "wx_openid_123456",
                    "nickname": "我是原生微信用户",
                    "headimgurl": "https://example.com/wechat_avatar.jpg",
                    "sex": 1,
                    "city": "深圳",
                    "province": "广东"
                ] as [String: Any],
                "accessToken": "fake_wechat_access_token_12345",
                "timestamp": Date().timeIntervalSince1970
            ]

            print("📱 微信登录成功，返回数据: \(wechatUserInfo)")
            result(wechatUserInfo)
        }
    }

    private func handleAlipayPayment(_ arguments: Any?, result: @escaping FlutterResult) {
        guard let paymentInfo = arguments as? [String: Any] else {
            result(FlutterError(code: "INVALID_ARGUMENT", message: "支付信息格式错误", details: nil))
            return
        }

        print("📱 开始模拟支付宝支付...")
        print("📱 支付信息: \(paymentInfo)")

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let paymentResult: [String: Any] = [
                "status": "success",
                "provider": "alipay",
                "orderId": paymentInfo["orderId"] ?? "unknown",
                "amount": paymentInfo["amount"] ?? 0,
                "transactionId": "alipay_tx_\(Int.random(in: 100000...999999))",
                "timestamp": Date().timeIntervalSince1970
            ]

            print("📱 支付宝支付成功，返回数据: \(paymentResult)")
            result(paymentResult)
        }
    }
}

// MARK: - 公共方法
extension ChannelManager {
    /// iOS端主动向Flutter端发送数据
    func sendDataToFlutter(data: [String: Any]) {
        print("📱 iOS端主动向Flutter发送数据: \(data)")

        DispatchQueue.main.async {
            // 使用dataChannel向Flutter发送数据
            self.dataChannel?.invokeMethod("iOSToFlutter", arguments: data)
        }
    }

    // 新增：开始模拟持续数据传递
    func startDataStream() {
        dataEventChannel?.startDataStream()
    }

    // 新增：停止数据流
    func stopDataStream() {
        dataEventChannel?.stopDataStream()
    }

    // 新增：手动发送数据
    func sendManualData(_ data: [String: Any]) {
        dataEventChannel?.sendManualData(data)
    }
}

